package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.itheima.constant.MessageConstant;
import com.itheima.entity.Result;
import com.itheima.pojo.Member;
import com.itheima.service.MemberService;
import com.qiniu.util.Json;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.Map;

@RestController
@RequestMapping("/member")
public class MemberController {
    @Reference
    private MemberService memberService;
    @Autowired
    private JedisPool jedisPool;

    @RequestMapping("/login")
    public Result login(@RequestBody Map map, HttpServletResponse resp) {
        //获取用户输入的验证码和手机号
        String validateCode = (String) map.get("validateCode");
        String telephone = (String) map.get("telephone");
        //通过手机号码查询是否已注册会员
        Member member = memberService.findByTel(telephone);
        //非会员自动注册
        if (member == null) {
            member = new Member();
            member.setRegTime(new Date());
            member.setPhoneNumber(telephone);
            memberService.add(member);
        } else {
            //该手机号已注册会员,则将会员的信息保存到cookie中
            Cookie cookie = new Cookie("", telephone);
            cookie.setPath("/");
            cookie.setMaxAge(60 * 60 * 24 * 30);
            //将响应添加Cookie
            resp.addCookie(cookie);
            //将会员信息转换为json类型
            String json = JSON.toJSON(member).toString();
            //将会员信息添加到redis中
            Jedis resource = jedisPool.getResource();
            resource.setex(telephone, 60 * 30, json);
            resource.close();
            //返回结果
            return new Result(true,MessageConstant.LOGIN_SUCCESS);
        }
        return new Result(false, MessageConstant.VALIDATECODE_ERROR);
    }
}
